package com.apkplug.download.serviceImp;

import java.io.File;
import java.io.IOException;
import org.apache.http.Header;
import android.content.Context;
import android.text.format.Formatter;
import com.apkplug.download.service.FileDownload;
import com.apkplug.download.service.FileDownloadCallBack;
import com.apkplug.loopj.android.HttpUtil.HttpUtil;
import com.apkplug.loopj.android.http.FileAsyncHttpResponseHandler;
public class DownloadServiceImp implements FileDownload{
	@Override
	public void download(Context mContext, String downurl,
			FileDownloadCallBack callback) throws IOException {
			
	}
	@Override
	public void download(final Context mContext, String downurl, String downFilePath,
			final FileDownloadCallBack callback) throws IOException {
		HttpUtil.get(downurl,new FileAsyncHttpResponseHandler(new File(downFilePath)) {
			int lastP = 0;
			String networkSpeed = "0B/s";
			int nowP = 0;
			@Override
			public void onProgress(int bytesWritten, int totalSize) {
				nowP=(int)(bytesWritten* 100 /totalSize);
				long spl = ((nowP - lastP)
                        * totalSize );
                networkSpeed = Formatter.formatFileSize(
                		mContext, spl > 0 ? spl : 0) + "/s";
                lastP = nowP;
                //Log.e("H3c", "p:" + nowP + "% speed:" + networkSpeed);
                callback.onProgress(bytesWritten, totalSize,networkSpeed);
				//super.onProgress(bytesWritten, totalSize);
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, File file) {
				callback.onFailure(statusCode, throwable.getMessage());
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers, File file) {
				callback.onDownLoadSuccess(file.getAbsolutePath());
			}	
		});
	}
}
